<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class DateRange implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $args = explode(',', $value);
        if (count($args) !== 2)
            return false;
        $from_time =strtotime($args[0]);
        $to_time = strtotime($args[1]);
        if ($from_time === false || $to_time === false || $from_time > $to_time)
            return false;
        return true;
    }

    /**
     * 格式化时间区间
     * @param $value
     */
    public static function format($value)
    {
        $args = explode(',', $value);
        if (count($args) !== 2)
            return [];
        $from_time =strtotime($args[0]);
        $to_time = strtotime($args[1]);
        return [date('Y-m-d 00:00:00', $from_time), date('Y-m-d 23:59:59', $to_time)];
    }
    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return ':attribute illegal date range pattern';
    }
}
